package sicnu.cs.aps.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sicnu.cs.aps.common.enums.ActivitySignEnum;
import sicnu.cs.aps.common.util.CollectionUtil;
import sicnu.cs.aps.domain.dto.ActivityInfoDto;
import sicnu.cs.aps.domain.dto.ActivityTotalMember;
import sicnu.cs.aps.domain.entity.Activity;
import sicnu.cs.aps.domain.entity.ActivityAudit;
import sicnu.cs.aps.domain.form.ActivityAuditForm;
import sicnu.cs.aps.domain.form.ActivityQueryForm;
import sicnu.cs.aps.domain.form.QueryForm;
import sicnu.cs.aps.domain.vo.ActivityAuditVo;
import sicnu.cs.aps.domain.vo.SimpleActivityVo;
import sicnu.cs.aps.mapper.*;
import sicnu.cs.aps.service.IActivityService;
import sicnu.cs.aps.service.IUserInfoService;

import java.lang.reflect.Array;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.*;
import java.util.stream.Collectors;

import static sicnu.cs.aps.common.util.RequestUtil.*;

/**
 * description 活动审核service实现类
 *
 * @author chenhetao
 * @version 1.0
 * @className ActivityServiceImpl
 * @packageName sicnu.cs.aps.service.impl
 * @date 2022/5/25 13:51
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    private final ActivityMapper activityMapper;
    private final UserMapper userMapper;
    private final ActivityAuditMapper auditMapper;
    private final IUserInfoService userService;
    private final ActivityTeamMapper teamMapper;
    private final ActivityRestrictionMapper restrictionMapper;
    private final Gson gson = new Gson();

    @Override
    public Long createActivity(Activity activity) {
        return activityMapper.addActivity(activity);
    }


    /**
     * 更新活动审核信息
     *
     * @param form
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doActivityAudit(ActivityAuditForm form) {
        int newState = Objects.requireNonNull(getNextState(form.getPass())).getIndex();
        if (isCurrentUserACollege() || isCurrentUserAUniversity()) {
            Long currentUserId = getCurrentUserId();

            //添加小队的审核信息记录
            auditMapper.insert(ActivityAudit.builder()
                    .activityId(form.getActivityId())
                    .auditedTeamId(form.getTeamId())
                    .type(newState)
                    .auditedTeamLeaderName(form.getCaptainName())
                    .auditedTeamId(form.getTeamId())
                    .opinion(form.getOpinion())
                    //审核人id
                    .optionUserId(currentUserId)
                    //TODO 测试
                    .optionUserName((gson.<HashMap<String, String>>fromJson(userService.getCurrentJSONedUserInfo(), HashMap.class)).get("name"))
                    .opinionTime(new Date())
                    .build());
            //更新小队的状态
            int i = teamMapper.updateStates(newState, form.getTeamId());
            if (i != 1) {
                throw new NoSuchElementException("修改小队状态失败");
            }
        } else {
            throw new NoSuchElementException("No Such Role!");
        }
    }

//    /**
//     * 分页查询活动审核情况
//     *
//     * @param form           分页信息
//     * @param roleUniversity 角色种类
//     * @return 活动审核信息列表
//     */
//    @Override
//    public PageInfo<ActivityAuditVo> listActivityAudit(ActivityAuditQueryForm form, String roleUniversity) {
//
//        PageHelper.startPage(form.getPageNum(), form.getPageSize());
//
//
//        if (roleUniversity.equals(Constants.ROLE_UNIVERSITY)) {
//            //学校查询
//            ActivityAudit activityAudit = new ActivityAudit();
//            BeanUtils.copyProperties(form, activityAudit, ActivityAudit.class);
//            List<ActivityAudit> activityAudits = auditMapper.selectByQueryPage(form);
//        } else {
//            //学院查询
//        }
//        return null;
//    }

    /**
     * 筛选活动
     *
     * @param queryForm 分页查询表
     * @param collegeId 学院id
     * @return
     */
    @Override
    public PageInfo<Activity> getActivityList(QueryForm queryForm, Long collegeId) {
        PageHelper.startPage(queryForm.getPageNum(), queryForm.getPageSize());
        return new PageInfo<>(activityMapper.selectActivityList(queryForm.getKeyword().trim(), collegeId));
    }

    /**
     * 获取所有活动
     *
     * @return 所有活动信息
     */
    @Override
    public List<SimpleActivityVo> getAllActivity() {
        List<SimpleActivityVo> activityAuditVoList = new ArrayList<>();
        activityMapper.selectList(null).forEach(activity -> activityAuditVoList.add(new SimpleActivityVo(activity.getId(), activity.getTitle())));
        return activityAuditVoList;
    }

    /**
     * 通过小队id列表查询所有活动
     *
     * @param teamIds 小队id列表
     * @return 活动列表
     */
    @Override
    public List<Activity> listByTeamIds(List<Long> teamIds) {
        return activityMapper.listActivityByTeamIds(teamIds);
    }

    /**
     * 查询活动统计信息列表
     * @param queryForm 分页信息 && type 1-已发布活动；2-未发布的活动（未到报名时间）;3-历史活动；其他：全部活动
     * @return 活动统计信息列表
     */
    @Override
    public PageInfo<ActivityInfoDto> selectActivityInfoList(ActivityQueryForm queryForm) {
        PageHelper.startPage(queryForm.getPageNum(), queryForm.getPageSize());
        List<ActivityInfoDto> activityInfoDtos = activityMapper.selectActivity(queryForm.getType());
        List<ActivityTotalMember> activityTotalMembers = activityMapper.countTotalMemberByActivityIdList(activityInfoDtos.stream().map(ActivityInfoDto::getId).collect(Collectors.toList()));
        for (ActivityInfoDto activityInfoDto : activityInfoDtos) {
            activityInfoDto.setCollegeIdList(CollectionUtil.separateStringExcludeEmpty(activityInfoDto.getCollegeIds()));
            activityInfoDto.setMajorIdList(CollectionUtil.separateStringExcludeEmpty(activityInfoDto.getMajorIds()));
            activityInfoDto.setGradeList(CollectionUtil.separateStringExcludeEmpty(activityInfoDto.getGrades()));
            for (ActivityTotalMember activityTotalMember : activityTotalMembers) {
                if (activityInfoDto.getId().equals(activityTotalMember.getActivityId())){
                    activityInfoDto.setTotalNum(activityTotalMember.getTotalNum());
                }
            }
        }
        return new PageInfo<>(activityInfoDtos);
    }

    /**
     * 通过传入的操作和当前身份返回下一个状态吗
     *
     * @param state 传入操作
     * @return 返回的状态码
     */
    private ActivitySignEnum getNextState(Integer state) {
        switch (state) {
            //通过
            case 1:
                if (isCurrentUserAUniversity()) {
                    //学校
                    return ActivitySignEnum.APPLY_SUCCESS;
                } else {
                    //学院
                    return ActivitySignEnum.UNIVERSITY_AUDIT_ON;
                }
                //驳回
            case 2:
                if (isCurrentUserAUniversity()) {
                    //学校
                    return ActivitySignEnum.UNIVERSITY_AUDIT_REBUT;
                } else {
                    //学院
                    return ActivitySignEnum.COLLEGE_AUDIT_REBUT;
                }
                //拒绝
            case 3:
                if (isCurrentUserAUniversity()) {
                    //学校
                    return ActivitySignEnum.UNIVERSITY_AUDIT_FAIL;
                } else {
                    //学院
                    return ActivitySignEnum.COLLEGE_AUDIT_FAIL;
                }
            default:
                return null;
        }
    }


}
